package com.yzr.common.asynchronous;

import sun.misc.Unsafe;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * 异步回调：CompletableFuture
 */
public class CompletableFutureUtil {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 无返回值
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            System.out.println("无返回值异步");
        });
        System.out.println("我先执行");
        future.get();
        Unsafe unsafe = Unsafe.getUnsafe();
        // 有返回值异步
        CompletableFuture<Integer> supplyAsync = CompletableFuture.supplyAsync(() -> {
            return 1024;
        });
        CompletableFuture<Integer> exceptionally = supplyAsync.whenComplete((t, u) -> {
            System.out.println("t=" + t);
            System.out.println("u=" + u);
        }).exceptionally((e) -> {
            System.out.println(e.getMessage());
            return 333;
        });
        Integer integer = exceptionally.get();
        System.out.println(integer);
    }
}
